﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using KC.Business;
using KC.DataAccess.InfoAggregator;

namespace KC.Presentation.InfoAggregatorService
{
	public partial class Service1 : ServiceBase
	{
		public Service1()
		{
			InitializeComponent();
		}
		public System.Timers.Timer timer1;
		private InfoDataContext dc;

		protected override void OnStart(string[] args)
		{
			dc = new InfoDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["Info"].ConnectionString);

			timer1 = new System.Timers.Timer();
			timer1.Interval = 10000;
			timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
			timer1.Enabled = true;
			timer1.Start();
		}

		void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
		{
			// Reset interval to tick more often
			if (timer1.Interval == 10000)
				timer1.Interval = 300000; // 300,000 ms = 5 minutes

			// Update RSS feeds
			AddDetail("Updating channels...");
			UpdateRssFeeds();
		}

		protected override void OnStop()
		{
			timer1.Dispose();
		}
		private void UpdateRssFeeds()
		{
			// Update RSS feeds
			try {
				int numChans = 0;
				foreach (RssChannel chan in dc.RssChannels) {
					string detail = "";
					try { 
						detail = KC.Business.InfoAggregator.DownloadNewItems(ref dc, chan);
						numChans++; }
					catch (Exception ex) { detail = ex.ToString(); }
					dc.Details.InsertOnSubmit(new Detail() { DateTime = DateTime.Now, text = detail }); }
				AddDetail("  " + numChans.ToString() + " of " + dc.RssChannels.Count().ToString() + " channels downloaded.");
				dc.SubmitChanges(); }
			catch (Exception ex) { Debug.WriteLine(ex.ToString()); }
		}
		private void AddDetail(string msg)
		{
			msg = msg.Trim() + "\r\n";
			dc.Details.InsertOnSubmit(new Detail() { DateTime = DateTime.Now, text = msg });
			dc.SubmitChanges();
		}

	}
}
